package com.zlzxm.studentscreen.util.applog;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;

import androidx.annotation.NonNull;


import com.zlzxm.studentscreen.globe.Constant;

import es.dmoral.toasty.Toasty;

/**
 * CREATE BY zlzxm ON 11/25/20
 */
public class AppUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{

    private static final String TAG = "AppUncaughtException";

    private Context appContext;

    private static final class  AppUncaughtExceptionHandlerHold{


        private static final AppUncaughtExceptionHandler HOLD = new AppUncaughtExceptionHandler();
    }

    private AppUncaughtExceptionHandler() {
    }


    public static AppUncaughtExceptionHandler getInstance() {
        return AppUncaughtExceptionHandlerHold.HOLD;
    }


    private Thread.UncaughtExceptionHandler defaultExceptionHandler;

    public void init(Context context){

        appContext = context;

        defaultExceptionHandler =  Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler(this);

    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {

        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toasty.error(appContext, "app出异常了,即将推出程序", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        recordError(e);

        defaultExceptionHandler.uncaughtException(t,e);



    }

    private void recordError(Throwable e){

        Logger.e(e,appContext.getExternalCacheDir()+ Constant.Path.LOG_ERROR);


    }




}
